from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from project_1.settings import BASE_DIR
import json

#  订单
def index(request):
	try:
		users = request.session.get('vipUser')['id']
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	# 获取当前用户
	user = models.Users.objects.get(id=request.session.get('vipUser')['id'])
	# 查看当前用户下的所以订单
	orders = models.Order.objects.filter(userid=user)
	# from django.core.paginator import Paginator
	# # 实例化分页类
	# paginator = Paginator(orders,5)

	# # 获取当前页码
	# p = int(request.GET.get('p',1))

	# # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
	# goodslist= paginator.page(p)

	# # 分配数据
	# # context = {'goods':goodslist}

	return render(request,'myhome/user_center_order.html',{"data":orders})

# 个人信息
def manage(request):
	try:
		# 获取用户对象
		user = models.Users.objects.get(id=request.session.get('vipUser')['id'])
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	return render(request,'myhome/user_center_info.html',{"user":user})
def infoUpdate(request):
	bj=request.GET.get("bj")
	val = request.GET.get("data")
	try:
		# 获取用户对象
		user = models.Users.objects.get(id=request.session.get('vipUser')['id'])
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	if bj == "name":
		# 获取用户
		user.username=val
		request.session['vipUser'] = {"username":val,"id":user.id,"phone":user.phone}
		user.save()
	elif bj == "pic_url":
		# 修改地址
		pass
	return HttpResponse("asd")






# 收货地址页面
def addrIndex(request):
	try:
		users = request.session.get('vipUser')['id']
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	# 获取省
	shen = models.Citys.objects.filter(level=1)
	users = request.session.get('vipUser')['id']
	# 地址
	try:
		addr = models.Address.objects.get(uid=users)
	except:
		addr=None
	return render(request,'myhome/user_center_site.html/',{"shen":shen,"addr":addr})


# 收货地址管理
def address(request):
	try:
		users = request.session.get('vipUser')['id']
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	try:
		addr = models.Address.objects.get(uid=users)
	except:
		addr=None
	alls = request.POST.dict()
	if addr == None:
		if alls['zhen']=="--请选择--"or alls['zhen']=="":
			alls['zhen']=""
		else:
			alls['zhen']=models.Citys.objects.get(id=int(alls['zhen'])).name
		alls.pop('csrfmiddlewaretoken')
		alls['uid']=models.Users.objects.get(id=users)
		alls['shen']=models.Citys.objects.get(id=int(alls['shen'])).name
		alls['shi']=models.Citys.objects.get(id=int(alls['shi'])).name
		alls['xian']=models.Citys.objects.get(id=int(alls['xian'])).name
		add = models.Address(**alls)
		add.save()
		return HttpResponse("<script>alert('添加成功');location.href='"+reverse('myhome_order_addrIndex')+"'</script>")
	try:
		if alls['zhen']=="--请选择--"or alls['zhen']=="":
			addr.zhen=""
		else:
			addr.zhen=models.Citys.objects.get(id=int(alls['zhen'])).name
		addr.uid=models.Users.objects.get(id=users)
		addr.shen=models.Citys.objects.get(id=int(alls['shen'])).name
		addr.shi=models.Citys.objects.get(id=int(alls['shi'])).name
		addr.xian=models.Citys.objects.get(id=int(alls['xian'])).name
		addr.phone = alls['phone']
		addr.code = alls['code']
		addr.username = alls['username']
		addr.info = alls['info']
		addr.save()
		return HttpResponse("<script>alert('修改成功');location.href='"+reverse('myhome_order_addrIndex')+"'</script>")
	except:
		return HttpResponse("<script>alert('修改失败');location.href='"+reverse('myhome_order_addrIndex')+"'</script>")
		
	

# 购买
def place_order(request):
	print(request.path)
	ids=eval(request.GET.get("data"))['id']
	num = eval(request.GET.get("data"))['num']
	good=[]
	for i in range(len(ids)):
		# 获取商品
		g1 = models.Goods.objects.get(id=int(ids[i]))
		# 添加总价属性
		g1.price_sum=int(num[i])*g1.price
		# 添加数量属性
		g1.num=int(num[i])
		# 添加一个索引   
		g1.ind=i+1
		good.append(g1)
	# 获取当前操作用户
	uid = request.session.get('vipUser')['id']
	user = models.Users.objects.get(id=uid)
	# 获取收货地址
	shou = models.Address.objects.filter(uid=user)
	return render(request,'myhome/place_order.html',{"data":good,'addr':shou})
# 购买成功
def over(request):
	import random
	res = request.GET.dict()
	# 生成订单编号
	dingId = random.randint(100000000000000000,99999999999999999999)
	# 订单id
	gid = res['gid'].split(",")
	# 订单数量
	num = res['num'].split(",")
	# 获取当前登录用户   
	user = models.Users.objects.get(id=request.session.get("vipUser")['id'])
	# 订单
	order = models.Order(address=res['addr'],priceSum=float(res['price']),mode=res['mode'],dingId=dingId,userid=user)
	order.save()
	# 获取刚更新数据的对象
	oid = models.Order.objects.last()
	# 订单详情
	for i in range(len(gid)):
		try:
			ors = models.OrderInfo.objects.get(gid=int(gid[i]),oid=oid)
			ors.num+=num[i]
			ors.save()
		except:
			good = models.Goods.objects.get(id=int(gid[i]))
			orderInfo = models.OrderInfo(gid=int(gid[i]),num=int(num[i]),oid=oid,pic_url=good.pic_url,title=good.title,price=good.price)
			orderInfo.save()
	# 获取当前用户
	# 成功后在购物车删除已买商品
	for i in gid:
		cart1 = models.Cart.objects.get(goodsid=models.Goods.objects.get(id=int(i)),uid=user)
		cart1.delete()
		pass
	return HttpResponse("asdsad")

# 删除订单
def orderDel(request):
	# 获取订单id
	oid = request.GET.get("id")
	# 给改订单修改状态
	order = models.Order.objects.get(id=oid)
	order.status = 2
	order.save()
	return HttpResponse("ok")

# 付款
def orderfu(request):
	# 获取订单id
	oid = request.GET.get("id")
	# 给改订单修改状态
	order = models.Order.objects.get(id=oid)
	order.status = 1
	order.save()
	return HttpResponse("ok")

# 城市
def citys(request):
	pid = request.GET.get("id")
	city = models.Citys.objects.filter(upid=pid).values()
	return HttpResponse(json.dumps(list(city)))


